package cn.mayday.algorithms.year2021.month1.A普通业务处理;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Semaphore;

/**
 * 实现一个容器，提供两个方法，add,size。
 * <p>
 * 写两个线程，线程1添加10个元素到容器中，线程2实现监控元素的个数，当个数到5个时，线程2给出提示并结束
 *
 * @author Mayday05
 * @date 2021/5/13 15:33
 */
public class Wuzong2 {

    public static void main(String[] args) throws InterruptedException {

        int[] input = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

        Semaphore semaphore1 = new Semaphore(1);
        Semaphore semaphore2 = new Semaphore(1);

        semaphore1.acquire();
        semaphore2.acquire();

        DefinedContainer definedContainer = new DefinedContainer();


        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for (int i = 0; i < input.length; i++) {
                        System.out.println("当前遍历" + input[i]);
                        definedContainer.add(input[i]);
                        if (i == 4) {
                            semaphore2.release(); // 等我执行到了，你才能开始，我会通知你

                            semaphore1.acquire(); // 然后我要等你执行完了，我才能继续添加，也就是我必须通知到你后，我才会继续干活
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }


            }
        });

        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    semaphore2.acquire();

                    System.out.println("已经达到五个，结束了");

                    semaphore1.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        });

        thread1.start();

        thread2.start();
    }

    public static class DefinedContainer {

        List list = new ArrayList<>();


        public void add(int input) {
            list.add(input);
        }

        public int size() {
            return list.size();
        }
    }
}
